package com.example.gfsquadwebviewproject.fragment.setting;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.gfsquadwebviewproject.R;
import com.example.gfsquadwebviewproject.activity.IActivityTouchEvent;
import com.example.gfsquadwebviewproject.activity.MainActivity;
import com.example.gfsquadwebviewproject.data.setting.SettingConfigData;
import com.example.gfsquadwebviewproject.fragment.BaseFragment;
import com.example.gfsquadwebviewproject.presenter.update.UpdateAppClassHolder;
import com.example.gfsquadwebviewproject.util.L;
import com.example.gfsquadwebviewproject.util.MyCountDownTimer;

public class SettingFragment extends BaseFragment implements MyCountDownTimer.ICountDownCallback {
    String TAG = "SettingFragment";

    Context context;

    LinearLayout back_setting;//返回
    TextView tv_setting_timeTick;//限时剩余时间显示
    TextView tv_version_name;//限时剩余时间显示
    Button bt_finish;//结束程序
    LinearLayout llaytou_all;
    LinearLayout lay_check_update;//检测更新

    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;

    ChangePasswordFragment changePasswordFragment;//修改密码
    UpgradeConfigFragment upgradeConfigFragment;//更新配置
    OtherSettingFragment otherSettingFragment;//其他设置
    MqttConfigFragment mqttConfigFragment;//mqtt

    MyCountDownTimer myCountDownTimer;//时间限时器
    SettingConfigData settingConfigData;//数据存储类

    IActivityTouchEvent iActivityTouchEvent;

    UpdateAppClassHolder updateAppClassHolder;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate");
        context = getContext();
        settingConfigData = new SettingConfigData(context);
        fragmentManager = getFragmentManager();
        changePasswordFragment = new ChangePasswordFragment();
        upgradeConfigFragment = new UpgradeConfigFragment();
        otherSettingFragment = new OtherSettingFragment();
        mqttConfigFragment = new MqttConfigFragment();
        updateAppClassHolder = UpdateAppClassHolder.instance(context);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.setting_fragment,container,false);
        back_setting = view.findViewById(R.id.back_setting);
        tv_setting_timeTick = view.findViewById(R.id.tv_setting_timeTick);
        tv_version_name = view.findViewById(R.id.tv_version_name);

        bt_finish = view.findViewById(R.id.bt_finish);
        llaytou_all = view.findViewById(R.id.llayout_all);

        lay_check_update = view.findViewById(R.id.lay_check_update);

        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //[1]获取包管理者对象 packageManager
        PackageManager pm = context.getPackageManager();
        try {
            //[2]从包管理者对象中获取指定包名的基本信息
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            //[3]获取版本名称，并返回
            tv_version_name.setText("版本号: "+packageInfo.versionName);

        }catch (Exception e){
            e.printStackTrace();
            L.wf(TAG,"获取版本号 error:"+e);
        }

        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.change_password,changePasswordFragment);
        fragmentTransaction.replace(R.id.upgrade_config,upgradeConfigFragment);
        fragmentTransaction.replace(R.id.other_setting,otherSettingFragment);
        fragmentTransaction.replace(R.id.fragment_mqtt_setting,mqttConfigFragment);
        fragmentTransaction.commit();

        llaytou_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager manager = ((InputMethodManager)getContext().getSystemService(getContext().INPUT_METHOD_SERVICE));
                if (manager != null)
                    manager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });

        //检测更新
        lay_check_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!updateAppClassHolder.getIsBusy()) {
                    updateAppClassHolder.compareVersions();
                }
                else {
                    Toast.makeText(getContext(),"正在更新中",Toast.LENGTH_LONG).show();
                }
            }
        });

        back_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iBaseFragmentBack.onBack(1);
            }
        });

        bt_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iBaseFragmentBack.onBack(0);
            }
        });

    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.d(TAG,"onAttach");
        iActivityTouchEvent = new IActivityTouchEvent() {
            @Override
            public void dispatchTouchEvent(MotionEvent ev) {
                //限时控件 检测是否触碰
                if (myCountDownTimer!=null) {
                    myCountDownTimer.dispatchTouchEvent(ev);
                }
            }
        };
        ((MainActivity)activity).setIActivityTouchEvent(iActivityTouchEvent);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG,"onResume");
        if (myCountDownTimer==null) {
            Log.d(TAG,"myCountDownTimer==null");
            //限时控件
            myCountDownTimer = new MyCountDownTimer(getContext(),this,settingConfigData.getSetting_view_timeout());
        }
        myCountDownTimer.start();
    }


    public void stopCountDownTimer(){
        myCountDownTimer.stop();
    }


    public void startCountDownTimer(){
        myCountDownTimer.start();
    }


    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG,"onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG,"onStop");

        iActivityTouchEvent = null;

        if (changePasswordFragment!=null) {
            changePasswordFragment.cleanView();
        }
        if (myCountDownTimer!= null) {
            //停止限时
            myCountDownTimer.stop();
            myCountDownTimer = null;
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            if (fragmentManager != null) {
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.remove(changePasswordFragment);
                fragmentTransaction.remove(upgradeConfigFragment);
                fragmentTransaction.remove(otherSettingFragment);
                fragmentTransaction.remove(mqttConfigFragment);
                fragmentTransaction.commitAllowingStateLoss();

                fragmentTransaction = null;
                fragmentManager = null;
            }
        }
        catch (Exception e){
            Log.d(TAG,"onDestroyView error:"+e);
        }Log.d(TAG,"onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy");
    }

    //限时倒计时
    @Override
    public void onTimeTick(int second) {
        tv_setting_timeTick.setText(""+second);
    }
    //限时 时间结束
    @Override
    public void onTimeOut() {
        iBaseFragmentBack.onBack(1);
    }


}